/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: RegisterHandle.java
 * Author: ckj
 * Date: 2024/7/21 下午9:28
 * Description:
 * 用于处理注册事件
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.handle;

import com.bosssoft.issue.BaseIssue;
import com.bosssoft.issue.RegisterIssue;
import com.bosssoft.message.RegisterMessage;
import com.bosssoft.message.ServerMessage;
import com.bosssoft.server.ChatServerWithClientIdentification;
import com.bosssoft.server.UserData;
import com.bosssoft.utils.WriterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;


/**
 * @author ckj
 */
public class RegisterHandle implements BaseHandle  {

    private static final Logger logger = LoggerFactory.getLogger(RegisterHandle.class);
    /**
     *
     * @author ckj
     * @date 2024/07/22 上午9:26
     * 处理
     */
    @Override
    public void handle(BaseIssue issue) {
        logger.info("用户正在注册");
        RegisterIssue registerIssue = (RegisterIssue) issue;
        RegisterMessage message = (RegisterMessage) registerIssue.getMessage();
        ChatServerWithClientIdentification.getClientMap().put(message.getUserName(), new UserData(registerIssue.getSocket()));
        ArrayList<String> content = new ArrayList<>();
        content.add("注册成功，您的 ID 为: " + message.getUserName());
        ServerMessage serverResponseMessage = new ServerMessage().build(content);
        try {
            WriterUtil.writeToUser(registerIssue.getWriter(),serverResponseMessage.convertFromTransferableDataList());
        } catch (Exception e) {
            logger.error("输入失败");
        }
        ChatServerWithClientIdentification.getUserObservers().forEach(userObserver -> {
            try {
                userObserver.updateNewUser(message.getUserName(), registerIssue.getSocket());
            } catch (IOException e) {
                logger.error("输入失败");
            }
        });
    }
}